package dev.alm.reggietakeoutservice.interceptor;

import com.alibaba.druid.util.StringUtils;
import dev.alm.reggietakeoutservice.utils.JedisUtil;
import dev.alm.reggietakeoutservice.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("AuthInterceptor preHandle");
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            log.info("token is invalid");
            throw new Exception("token is invalid");
        }
        Claims claims = JwtUtil.parseJwt(token);
        if (claims == null) {
            log.info("token is invalid");
            throw new Exception("token is invalid");
        }
        String username = claims.getSubject();
        Jedis jedis = JedisUtil.getJedisPoolInstance().getResource();
        String s = jedis.get(username);
        if (StringUtils.isEmpty(s)) {
            log.info("token is invalid");
            throw new Exception("token is invalid");
        }
        if (!token.equals(s)) {
            log.info("token is invalid");
            throw new Exception("token is invalid");
        }
        // 将token的有效期设置为3600秒
        jedis.expire(username, 3600);
        JedisUtil.release(jedis);
        return true;
    }

}
